package com.jrx.anytxn.feign.filter;

import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @comment: 自定义请求日志追踪过滤器
 * @author: hsoong
 * @date: 2021/12/3 22:14
 */
@Component
public class CustomTraceFilter extends OncePerRequestFilter implements Ordered {

    public static final String HEADER_REQUEST_ID = "X-Request-Id";

    public static final String LOG_LABEL = "RequestId";

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String value = request.getHeader(HEADER_REQUEST_ID);
        if (StringUtils.isEmpty(value)) {
            value = UUID.randomUUID().toString();
        }

        MDC.put(LOG_LABEL, value);
        response.setHeader(HEADER_REQUEST_ID, value);

        try {
            filterChain.doFilter(request, response);
        } finally {
            MDC.remove(LOG_LABEL);
        }
    }


}
